package com.eastdigit.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("unchecked")
public class ServletUtil {
    public static String getHomeURL(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }

    public static Map getParameterMap(HttpServletRequest request) {
        return getParameterMap(request, true);
    }

    public static Map getParameterMap(HttpServletRequest request, boolean otherFlag) {
        Map map = new HashMap();
        Map tmap = request.getParameterMap();
        Object[] keys = tmap.keySet().toArray();
        for (int i = 0; i < tmap.size(); i++) {
            Object key = keys[i];
            Object value = tmap.get(key);
            if (value == null) {
                map.put(key, null);
            }
            if (!value.getClass().isArray()) {
                map.put(key, value);
            } else {
                String[] arr = (String[]) value;
                if (arr.length == 1) {
                    map.put(key, arr[0]);
                } else {
                    StringBuffer sb = new StringBuffer();
                    for (int k = 0; k < arr.length; k++) {
                        if (k != 0) {
                            sb.append(",");
                        }
                        sb.append(arr[k]);
                    }
                    map.put(key, sb.toString());
                }
            }
        }
        return map;
    }

    public static Map<String, String> getMapFromQueryString(String url) {
        Map<String, String> map = new HashMap<String, String>();
        int index = url.indexOf('?');
        if (index < 0) {
            return map;
        } else {
            String str = url.substring(url.indexOf('?') + 1);
            int index2 = str.lastIndexOf('#');
            if (index2 != -1) {
                str = str.substring(0, index2);
            }
            String[] arr = str.split("\\&");
            for (int i = 0; i < arr.length; i++) {
                String[] arr2 = arr[i].split("\\=");
                if (arr2.length == 2) {
                    map.put(arr2[0], arr2[1]);
                } else {
                    map.put(arr2[0], "");
                }
            }
            return map;
        }
    }

    public static String getParamString(Map map) {
        return getParamString(map, false);
    }

    public static String getParamString(Map map, boolean encodeFlag) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append("?");
        Object[] ks = map.keySet().toArray();
        Object[] vs = map.values().toArray();
        for (int i = 0, j = 0; i < map.size(); i++) {
            if (vs[i] == null) {
                continue;
            }
            if (j != 0) {
                sb.append("&");
            }
            sb.append(ks[i] + "=");
            if (encodeFlag) {
                sb.append(StringUtil.urlEncode(vs[i].toString()));
            } else {
                sb.append(vs[i].toString());
            }
            j = 1;
        }
        return sb.toString();
    }

    public static String getURLContent(String strurl) throws Exception {
        StringBuffer sb = new StringBuffer();
        URL url = new URL(strurl);
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        String s = null;
        while ((s = br.readLine()) != null) {
            sb.append(s);
            sb.append("\n");
        }
        br.close();
        return sb.toString();
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        return getCookieValue(request, cookieName, "");
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue) {
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookieName.equalsIgnoreCase(cookie.getName()))
                return StringUtil.unescape(cookie.getValue());
        }
        return defaultValue;
    }

    public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String cookieName,
            String cValue) {
        setCookieValue(request, response, cookieName, 60 * 60 * 24 * 31, cValue);
    }

    public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String cookieName,
            int maxAge, String cValue) {
        Cookie[] cookies = request.getCookies();
        boolean cookieexistflag = false;
        cValue = StringUtil.escape(cValue);
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookieName.equalsIgnoreCase(cookie.getName())) {
                cookieexistflag = true;
                cookie.setValue(cValue);
                cookie.setMaxAge(maxAge);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        if (!cookieexistflag) {
            Cookie cookie = new Cookie(cookieName, cValue);
            cookie.setMaxAge(maxAge);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    public static String getUrlExtension(String url) {
        int index = url.indexOf('?');
        if (index > 0) {
            url = url.substring(0, index);
        }
        int i1 = url.lastIndexOf('/');
        int i2 = url.lastIndexOf('.');
        if (i1 >= i2) {
            return "";
        } else {
            return url.substring(i2).toLowerCase();
        }
    }

    public static String getFileName(String url) {
        int index = url.indexOf('?');
        if (index > 0) {
            url = url.substring(0, index);
        }
        int i1 = url.lastIndexOf('/');
        return url.substring(i1 + 1);
    }

    public static String getHost(String url) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            System.out.println("错误的URL：" + url);
            return null;
        }
        int index = url.indexOf("//") + 2;
        int index2 = url.indexOf("/", index);
        if (index2 <= 0) {
            index2 = url.length();
        }
        return url.substring(index, index2);
    }

}
